package com.example.cjh.mymusic;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import java.io.IOException;

public class PlayServer extends Service {
    private bcRecevier rceiver = new bcRecevier();
    private MediaPlayer mediaPlayer = new MediaPlayer();
    public static int position = -1;//播放歌曲在list里面的位置
    private MusicApi musicApi;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        Log.i("输出", "初始化广播");
        //定义广播接收器，用于接收音乐操作（播放，暂停，切歌）
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BroadCastBean.bcNextOrBefore);
        intentFilter.addAction(BroadCastBean.bcPlayOrPause);
        intentFilter.addAction(BroadCastBean.bcReplay);
        intentFilter.addAction(BroadCastBean.bcMusicPro);
        intentFilter.addAction(BroadCastBean.bcSetMusicPro);
        registerReceiver(rceiver, intentFilter);
        super.onCreate();
    }


    @Override
    public void onDestroy() {
        unregisterReceiver(rceiver);
        super.onDestroy();
    }

    //广播接收类的定义
    public class bcRecevier extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(BroadCastBean.bcPlayOrPause)) {
                //继续播放或者暂停播放
                playOrPauseMusic();
            } else if (action.equals(BroadCastBean.bcReplay)) {
                //重新播放或者切歌
                Log.i("输出", "切歌广播");
                int position = intent.getIntExtra("newPosition", -1);
                if (position != -1) {
                    rePlay(position);
                }
            } else if (action.equals(BroadCastBean.bcNextOrBefore)) {
                //上一首或者下一首nob -- next or before position
                int position = intent.getIntExtra("nobPosition", -1);
                if (position != -1) {
                    nextMusic(position);
                }
            } else if (action.equals(BroadCastBean.bcMusicPro)) {
                //获取播放进度
                if (getPro() != -1) {
                    musicApi = MainActivity.mainActivity;
                    musicApi.MusicDuration(getPro());
                }
            } else if (action.equals(BroadCastBean.bcSetMusicPro)) {
                int pro = intent.getIntExtra("musicPro", -1);
                if (pro != -1) {
                    if(mediaPlayer!=null){
                        mediaPlayer.seekTo(pro);
                    }
                }
            }
        }
    }

    //获取mediaplay的播放进度
    private int getPro() {
        if (mediaPlayer != null) {
            if (mediaPlayer.getCurrentPosition() != mediaPlayer.getDuration())
                return mediaPlayer.getCurrentPosition();
        } else
            return -1;
        return -1;
    }


    //继续或者继续音乐的函数

    private void playOrPauseMusic() {
        if (mediaPlayer != null) {
            if (!mediaPlayer.isPlaying()) {
                mediaPlayer.start();
                musicApi = MainActivity.mainActivity;
                initfinishMonitor();
            } else {
                mediaPlayer.pause();
            }
        }
    }


    //重新播放音乐函数--用于首次播放歌曲或者切换歌曲
    private void rePlay(int position) {
        this.position = position;
        try {
            Log.i("输出", "rePlay路径" + BroadCastBean.musicList.get(position).getPath() + "");
            mediaPlayer.reset();
            mediaPlayer.setDataSource(BroadCastBean.musicList.get(position).getPath());
            mediaPlayer.prepare();
            mediaPlayer.start();
            updateUi();
            initfinishMonitor();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //播放下一首/上一首歌曲  key用于标识是上一首韩式下一首，这里1是上一首,2是下一首
    private void nextMusic(int key) {
        if (key == 1) {
            position = position - 1;
        } else if (key == 2) {
            position = position + 1;
        }
        if (BroadCastBean.musicList.size() > position && position >= 0) {
            //下一首或者上一首存在歌曲了
            if (mediaPlayer != null) {
                try {
                    mediaPlayer.reset();
                    mediaPlayer.setDataSource(BroadCastBean.musicList.get(position).getPath());
                    mediaPlayer.prepare();
                    mediaPlayer.start();
                    updateUi();
                    initfinishMonitor();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            //下一首或者上一首已经没有歌曲了
        }
    }

    //初始化mediaplay播放完毕的监听
    private void initfinishMonitor() {
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                //播放完毕
                musicApi.MusicPlayFinish(true);
            }
        });

    }

    //更新播放信息的函数
    public void updateUi() {
        musicApi = MainActivity.mainActivity;
        musicApi.MusicInfo(0,
                BroadCastBean.musicList.get(position).getSong(),
                BroadCastBean.musicList.get(position).getDuration());
    }


}
